#!/usr/bin/env python

#demo

import os
import sys
import inspect
import threading
import time
import ctypes
import thread

def get_thread_id():
	SYS_gettid = 186
	libc = ctypes.cdll.LoadLibrary('libc.so.6')
	tid = libc.syscall(SYS_gettid)
	return tid

def test():
	print "come in=",__name__
	print "curdir=" , os.path.abspath(os.curdir)

	list_threads=[]
	for i in range(1,5):
		print i," say hello."
		tmp=mythread("thr_"+str(i))
		list_threads.append(tmp)
	#start threads
	for tmp in list_threads:
		tmp.start()

	return

class mythread(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)

    def run(self):
        global x
        lock.acquire()
        for i in range(3):
            x=x+1
        time.sleep(1)
        print self.getName(),"value=",x
        lock.release()
        print "-->",self.getName()
        f01()

	return	

def f01():
	#print get_thread_id() 
	print "come in=",sys._getframe(0).f_code.co_name
	print "cur_thread=",thread.get_ident()
	return

def t01(value=1):
	print "arg=",value ,"\tcome in=",sys._getframe(0).f_code.co_name
	#print inspect.stack()
	stack_print(inspect.stack())
	return

def t02(value=2):
	print "arg=",value ,"\tcome in=",sys._getframe(0).f_code.co_name
	t01()
	return

def t03(value=3):
	print "arg=",value ,"\tcome in=",sys._getframe(0).f_code.co_name
	t02()
	return

def t04(value=4):
	print "arg=",value ,"\tcome in=",sys._getframe(0).f_code.co_name
	t03()
	return

def stack_print(stack_list):
	print "----------stack display------------"
	print "cur_thread=",thread.get_ident()
	for tmp in stack_list:
		print "\t",tmp
	print "----------stack end------------"
	return

if __name__ == '__main__':

	print "hello"
	x=0   #global test value.
	lock=threading.RLock()

	test()  #test threads

	t04()  #test callstack

	
	